<template>
	<view>
		<view class="userAuth" v-if="show">
			<view class='header row-center-center'>
				<view class="avatar">
					<open-data  type="userAvatarUrl"></open-data>
				</view>
			</view>
			<view class='content'>
			  <view>消息订阅需申请获取以下权限</view>
			  <text>获得你的公开信息(昵称，头像、地区等)</text>
			</view>
			<button class="authBtn" type='primary' open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="userAuthHandle">确认授权</button>
		</view>
		<view class="" v-if="!show">
			<u-cell-group title="订阅该消息可获取最新消息推送：" title-style="{'fontSize': '35rpx'}">
					<u-cell-item icon="arrow-right" title="审核信息提示" :arrow="false"></u-cell-item>
					<u-cell-item icon="arrow-right" title="审核结果提示" :arrow="false"></u-cell-item>
					<u-cell-item icon="arrow-right" title="最新任务提示" :arrow="false"></u-cell-item>
			</u-cell-group>
			<button class="authBtn" type='primary' :disabled="isOpen" @click="openMsg">{{btnMsg}}</button>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import { mapState,mapMutations} from 'vuex';
	export default {
		computed:mapState(['user', ]),
		data(){
			return {
				show:false,
				params:{
					encryptedData:'',
					iv:'',
					code:'',
					id:''
				},
				templateIds:['hkrNC4RnWG2stbXFskoxA3TvbRzSH0DY1l-EHiTzBEE',],
				isOpen:false,
				btnMsg:'开启消息订阅'
			}
		},
		methods:{
			...mapMutations(['updateUserInfo']),
			// 用户是否授权，用于获取openid
			checkUserAuth(){
				var _this = this;
				uni.getSetting({
				    success(res){
				        if(res.authSetting['scope.userInfo']){
				            _this.show = false;
				        }else if(!res.authSetting['scope.userInfo']){
							_this.show = true;  
				        }
				    }
				}) 
			},
			userAuthHandle() {
			    // 重赋值this
			    var _this=this;
			    // 获取用户授权设置
			    uni.getSetting({
			        success(res){
			            if(res.authSetting['scope.userInfo']){
			                // 如果要获取的权限已经授权,则直接获取相关信息
			                uni.getUserInfo({
			                    success(res){
			                        // 获取相关数据后，进行登录及数据请求
			                        _this.handleLogin(res);
			                    },
			                    fail(err){
			                        // 错误信息
			                        console.log(err)
			                    }
			                })
			            }else if(!res.authSetting['scope.userInfo']){
							_this.show = true;
			                // 如果要获取的权限尚未授权,则此时触发授权，打开设置页面
			                uni.showModal({
			                    //弹出提示框
			                    title: '是否打开设置页？',
			                    content: '需要在设置中获取用户信息',
			                    success(res) {
			                        if (res.confirm) {
			                            uni.openSetting({
			                                // 弹出框，确认后打开设置页面
			                                success(res) {
			                                    console.log(res.authSetting)
			                                },    
			                            })
			                        } else if (res.cancel) {
			                            console.log('用户点击取消');
			                        }
			                    }
			                });    
			            }
			        }
			    })    
			},
			// 执行登录,数据请求的方法
			handleLogin(infoRes){
				var _this=this;
				console.log(infoRes);
			    this.params.encryptedData=infoRes.encryptedData;//用户信息的加密数据串
			    this.params.iv=infoRes.iv;//加密算法秘钥
				uni.login({
					provider: 'weixin',
				    success(res){
				        if(res.code){
							_this.params.code = res.code;
							//获取用户信息
							_this.getUserInfo(_this.params);
							/* uni.switchTab({
								url:'../index/index'
							}); */
				            
				        }else{
				            // 无code时不执行数据请求
				            console.log("无code")
				        }    
				    },
				    fail(err){
				        console.log("授权失败")
				    }
				})
				// 检测sessionkey是否过期 1未过期 0已过期
				/* uni.checkSession({					
					success(res) {		//状态未过期
						console.log("session_key未过期");
						console.log(res);
						//_this.updateUserInfo(data);
					},
					fail() {		//状态已过期
						uni.login({
							provider: 'weixin',
						    success(res){
						        if(res.code){
									_this.params.code = res.code;
									//获取用户信息
									_this.getUserInfo(_this.params);
						            
						        }else{
						            // 无code时不执行数据请求
						            console.log("无code")
						        }    
						    },
						    fail(err){
						        console.log("授权失败")
						    }
						})
					}
				}) */
			    
			},
			
			getUserInfo(obj){
				// 登录成功后且code存在，则进行数据请求
				this.$http.post("/check/userInfo",obj).then(res=>{
					let data = res.data.data;
					if(data){
						this.show = false;
						console.log(data);
						uni.setStorage({
							key:"userInfo",
							data:data
						});
						this.updateUserInfo(data);
					}else{
						this.show = true;
					}
					console.log(res);
				}).catch(err => {
					this.$refs.uToast.show({
						title: '授权失败！',
						type: 'error'
					}) 
				})
			},
			// 消息订阅开启
			openMsg(){
				var _this = this;
				uni.requestSubscribeMessage({
				  tmplIds: this.templateIds,
				  success(res){
					  if(res[_this.templateIds[0]]==="accept"){
						  _this.$http.get("/user/openMsg",{params:{id:_this.params.id}}).then(res=>{
							  let data = res.data.data;
							  if(data){
								  uni.setStorage({
								  	key:"userInfo",
								  	data:data
								  });
								  _this.isOpen = true;
								  _this.btnMsg = '已订阅该消息';
								  _this.updateUserInfo(data);
								  _this.$refs.uToast.show({
								  	title: '订阅成功',
								  	type: 'success'
								  }) 
							  }
						  })
					  }else if(res[_this.templateIds[0]]==="reject"){
						  _this.$refs.uToast.show({
						  	title: '您放弃了消息订阅',
						  	type: 'error'
						  }) 
						  console.log("拒绝了消息开启");
					  }
				  },
				  fail(err){
					  console.log(err);
				  }
				})
			}
		},
		onLoad() {
			this.params.id = this.user.user.id;
			if(!this.user.user.openId){
				this.checkUserAuth();
			}
			if(this.user.user.isOpenMsg === '1'){
				this.isOpen = true;
				this.btnMsg = '已订阅该消息';
			}
		}
	}
</script>

<style lang="scss" scoped>
	.header {
		border-bottom: 1px solid #ccc;
		text-align: center;
		width: 100%;
		height: 300rpx;
	}
	.avatar{
		width: 150rpx;
		height: 150rpx;
		border-radius: 50%;
	}
	.content {
		margin-left: 50rpx;
		margin-bottom: 90rpx;
	}
	.content text {
		display: block;
		color: #9d9d9d;
		margin-top: 40rpx;
	}
	.authBtn{
		margin: 70rpx 50rpx;
	}
	.title{
		font-size: 40rpx;
		line-height: 45rpx;
		margin: 15rpx;
		
	}
	.list{
		font-size: 35rpx;
		line-height: 50rpx;
		text-indent: 48rpx;
		color: #9d9d9d;
		margin: 20rpx;
	}
</style>
